const {createCanvas,loadImage} = require('canvas')
const ratio = 0.1
function watermark(pic,wm) {
    loadImage(pic).then(myimg =>{
        loadImage(wm).then(wmimg =>{
            const canvas = createCanvas(myimg.width,myimg.height)
            const ctx = canvas.getContext('2d')
            ctx.drawImage(myimg,0,0)
            //计算旋转贴图的最大需要尺寸 矩形的对角线
            const long = Math.sqrt(wmimg.width * wmimg.width + wmimg.height * wmimg.height)
            const halfong = long/2
            //获取背景图的最长边长
            const bglong = Math.max(myimg.width,myimg.height)
            //计算贴图的比例缩放
            const signscale = bglong / long * ratio
            //题图的缓步边长按比例缩放
            const vmlong = long * signscale
            //创建贴图的画布
            const canvas1 = createCanvas(vmlong,vmlong)
            //获取贴图的绘图区
            const ctx1 = canvas1.getContext('2d')
            //贴图绘图区缩放
            ctx1.scale(signscale,signscale)
            //绘图区移到中心点
            ctx1.translate(halfong,halfong)
            //贴图绘图区绕中心点旋转随机角度
            ctx.rotate((Math.random()-0.5) * Math.PI / 2)
            //绘图区移到原点
            ctx1.translate(-halfong,-halfong)
            //绘制贴图区到贴图绘图区
            ctx1.drawImage(wmimg,(long-wmimg.width) / 2, (long-wmimg.height) / 2)
            //随机生成背景图上的粘贴位置
            const posx = (myimg.width-vmlong) * Math.random()
            const posy = (myimg.height - vmlong) * Math.random()
            //绘图绘制到背景图
            ctx.drawImage(canvas1,posx,posy)

            const fs = require('fs')
            const out = fs.createWriteStream(__dirname + '/' + pic)
            const stream = canvas.createPNGStream()
            stream.pipe(out)
            out.on('finish',()=>console.log('PNG file created.'))
        })
    })
}
module.exports = watermark
//  watermark('bg.png','watermark.png')